package com.itheima.canal.listener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.itheima.canal.config.RabbitMQConfig;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 1: 监控goods库中的spu表
 * 2: is_marketable 0-> 1 上架
 * 3  spuId发送到 mq
 */
@CanalEventListener
public class SpuListener {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * spu 表更新
     *
     * @param eventType 事件类型
     * @param rowData   行数据
     */
    @ListenPoint(schema = "changgou_goods", table = "tb_spu")
    public void spuUp(CanalEntry.EventType eventType, CanalEntry.RowData rowData) {
        System.out.println("tb_spu表数据发生变化");

        //改变之前的列和值得map
        Map<String, String> beformap = new HashMap<>();
        //获取改变之前的列和值
        List<CanalEntry.Column> beforeColumnsList = rowData.getBeforeColumnsList();
        /*
        for (CanalEntry.Column column : beforeColumnsList) {
            //某一列列名
            String name = column.getName();
            //某一列值
            String value = column.getValue();
            beformap.put(name,value);
        }
        */
        beforeColumnsList.forEach(column -> beformap.put(column.getName(), column.getValue()));

        //获取改变之后的列和值
        Map<String, String> nowMap = new HashMap<>();
        List<CanalEntry.Column> afterColumnsList = rowData.getAfterColumnsList();
        afterColumnsList.forEach(column -> nowMap.put(column.getName(), column.getValue()));

        //2: is_marketable 0-> 1 上架
        if (beformap.get("is_marketable").equals("0") && nowMap.get("is_marketable").equals("1")){
            //spuId发送到 mq
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_UP_EXCHANGE,"",nowMap.get("id"));
        }

        //3: is_marketable 1-> 0 上架
        if (beformap.get("is_marketable").equals("1") && nowMap.get("is_marketable").equals("0")){
            //spuId发送到 mq
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_DOWN_EXCHANGE,"",nowMap.get("id"));
        }
        //4.获取最新审核通过商品 status 0->1
        if (beformap.get("status").equals("0") && nowMap.get("status").equals("1")){
            //spuId发送到 mq
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_UP_EXCHANGE,"",nowMap.get("id"));
        }
    }
}
